package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;


    /**
     * 保存本地交易记录
     *
     * @param paymentType 支付类型  支付类型：1301-订单 1302-充值
     * @param orderNo     订单编号
     * @param userId      用户ID
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo, Long userId) {
        //1.根据订单编号查询本地交易记录 如果存在则返回即可
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfoDB = this.getOne(queryWrapper);
        if (paymentInfoDB != null) {
            return paymentInfoDB;
        }
        //2.构建本地交易记录对象
        paymentInfoDB = new PaymentInfo();
        //2.1 基本属性赋值 用户ID、交易类型、订单编号、付款方式（微信）、交易状态：未支付(1401)
        paymentInfoDB.setUserId(userId);
        paymentInfoDB.setOrderNo(orderNo);
        paymentInfoDB.setPaymentType(paymentType);
        paymentInfoDB.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfoDB.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //2.2 封装交易内容及金额（远程调用订单服务或者账户服务获取）
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //远程调用订单服务获取订单金额及购买项目（VIP会员，专辑、声音）
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在！");
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
                throw new GuiguException(211, "订单状态错误！");
            }
            paymentInfoDB.setAmount(orderInfo.getOrderAmount());
            paymentInfoDB.setContent(orderInfo.getOrderTitle());
        } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //远程调用账户服务获取充值金额
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值记录不存在！");
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())) {
                throw new GuiguException(211, "充值订单状态错误！");
            }
            paymentInfoDB.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfoDB.setContent("充值" + rechargeInfo.getRechargeAmount());
        }
        //3.保存本地交易记录且返回
        this.save(paymentInfoDB);
        return paymentInfoDB;
    }

    /**
     * 在支付成功后同步调用，异步调用都调用该方法完成支付系统，订单系统，账户系统后续业务
     * 修改本地交易记录,更新回调字段，交易状态：已支付
     * * 处理订单-远程调用订单服务修改订单状态以及用户购买记录新增
     * * 处理充值-远程调用账户服务充值余额及变动日志新增
     *
     * @param transaction 微信响应交易对象
     */
    @Override
    public void updatePaymentInfoSuccess(Transaction transaction) {
        //1.根据订单编号查询本地交易记录-获取交易记录状态 如果已支付，说明已经处理过返回即可
        String orderNo = transaction.getOutTradeNo();
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        if (paymentInfo != null && SystemConstant.PAYMENT_STATUS_PAID.equals(paymentInfo.getPaymentStatus())) {
            return;
        }
        //2.更新本地交易记录支付回调信息，及交易状态：已支付
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        this.updateById(paymentInfo);

        //3.判断支付类型：1301-订单  远程调用订单服务修改订单及新增购买记录
        if(SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())){
            Result result = orderFeignClient.orderPaySuccess(orderNo);
            if (200 != result.getCode()) {
                throw new GuiguException(212, "修改订单异常");
            }
        }
        //4.判断支付类型 1302-充值
        if(SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())){
            Result result = accountFeignClient.rechargePaySuccess(orderNo);
            if (200 != result.getCode()) {
                throw new GuiguException(212, "充值异常");
            }
        }
    }
}
